﻿
using Scaffold.AppService.Interfaces;
using Scaffold.AppService.Model.RequestModel;
using Scaffold.Domain;
using Scaffold.Domain.Model;
using EStart.DataBase.EF;
using EStart.DataBase.Event.Domian;
using EStart.Infrastructure.ClientData;
using QuestionBank.Infrastructure.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Scaffold.AppService.Model.Messaging;
using Scaffold.AppService.Model.ResponseModel;
using EStart.Infrastructure.Domain;
using Microsoft.EntityFrameworkCore;
using EStart.Infrastructure.Extensions;
using Scaffold.AppService.Extensions;
using Scaffold.AppService.Model.Models;
using EStart.Infrastructure.Domain.Events;

namespace Scaffold.AppService.Implements
{
    public partial class UserMenuService : ServiceCore<UserMenu>, IUserMenuService
    {
        private readonly IUserActionService _userActionService;

        public UserMenuService(
            ScaffoldDbContext context,
            EventDbContext eventDbContext,
            IUserActionService userActionService
            ) : base(context, eventDbContext)
        {
            _userActionService = userActionService;
        }

        public async Task<ApiResult<Tree>> GetCheckModelAsync()
        {
            ApiResult<Tree> response = new ApiResult<Tree>();
            try
            {

                var allMenu = await Query().Select(n => new
                {
                    n.UserMenuID,
                    n.ID,
                    n.Name
                }).ToListAsync();
                var allAction = await _userActionService.Query().Select(n => new
                {
                    n.ID,
                    n.Name
                }).ToListAsync();
                //组装
                Tree alltree = new Tree();
                alltree.expandKey = new List<string>();
                alltree.treeModel = new List<TreeModel>();
                var fatherMenu = allMenu.Where(n => n.UserMenuID == null).ToList();
                var childMenu = allMenu.Where(n => n.UserMenuID != null).ToList();
                foreach (var item in fatherMenu)
                {
                    TreeModel tree = new TreeModel();
                    alltree.expandKey.Add(item.ID.ToString());
                    tree.key = item.ID.ToString();
                    tree.title = item.Name;
                    tree.children = new List<TreeModel>();
                    childMenu.Where(n => n.UserMenuID == item.ID)
                    .ForEach(n =>
                    {
                        var model = new TreeModel
                        {

                            key = item.ID + "-" + n.ID,
                            title = n.Name,
                            children = allAction.Select(c => new TreeModel
                            {
                                key = item.ID + "-" + n.ID + '-' + c.ID,
                                title = c.Name
                            }).ToList()
                        };

                        alltree.expandKey.Add(item.ID + "-" + n.ID);
                        tree.children.Add(model);
                    });

                    alltree.treeModel.Add(tree);
                }
                response.success = true;
                response.data = alltree;
                response.message = "获取成功！";
                return response;
            }
            catch (Exception ex)
            {
                response.message = "获取失败！意外错误:" + ex.Message;
                return response;
            }
        }
        public ApiResult<string> Delete(Guid guid)
        {
            ApiResult<string> response = new ApiResult<string>();
            try
            {

                var school = Query().Where(n => n.Guid == guid).FirstOrDefault();
                if (school == null)
                {
                    response.message = "未找到改数据！";
                    return response;
                }
                DeleteForge(school);
                var b = _unitofwork.Commit();
                response.success = b;
                response.message = b ? "删除成功！" : "删除失败！";
                return response;
            }
            catch (Exception ex)
            {
                response.message = "删除失败！意外错误:" + ex.Message;
                return response;
            }
        }

        public ApiResult<UserMenuModel> GetDetail(Guid guid)
        {
            ApiResult<UserMenuModel> response = new ApiResult<UserMenuModel>();
            try
            {

                var entity = Query().Where(n => n.Guid == guid)
                    .Include(n => n.UserMenuChild)
                    .Select(n => new UserMenuModel
                    {
                        CreateTime = n.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        guid = n.Guid.ToString(),
                        Name = n.Name,
                        FatherID = n.UserMenuID,
                        Icon = n.Icon,
                        Introduce = n.Introduce,
                        Spread = n.Spread,
                        Url = n.Url

                    }).FirstOrDefault();
                if (entity == null)
                {
                    response.message = "未找到改数据！";
                    return response;
                }
                response.success = true;
                response.data = entity;
                response.message = "获取成功！";
                return response;
            }
            catch (Exception ex)
            {
                response.message = "获取失败！意外错误:" + ex.Message;
                return response;
            }
        }

        public async Task<ApiResult<Page<UserMenuModel>>> GetPagesAsync(UserMenuPage request)
        {
            ApiResult<Page<UserMenuModel>> response = new ApiResult<Page<UserMenuModel>>();
            try
            {
                var childpages = await Query()
                               .Where(n => n.UserMenuID != null)
                               .Select(n => new UserMenuModel
                               {
                                   key = n.ID,
                                   CreateTime = n.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                   guid = n.Guid.ToString(),
                                   Name = n.Name,
                                   FatherID = n.UserMenuID,
                                   Icon = n.Icon,
                                   Introduce = n.Introduce,
                                   Spread = n.Spread,
                                   Url = n.Url,
                               }).OrderBy(n => n.Sort).ToListAsync();
                var pages = await Query()
                               .HasWhere(request.MenuName, n => n.Name.Contains(request.MenuName))
                               .Where(n => n.UserMenuID == null)
                               .Select(n => new UserMenuModel
                               {
                                   key = n.ID,
                                   CreateTime = n.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                   guid = n.Guid.ToString(),
                                   Name = n.Name,
                                   FatherID = n.UserMenuID,
                                   Icon = n.Icon,
                                   Introduce = n.Introduce,
                                   Spread = n.Spread,
                                   Url = n.Url,
                                   children = childpages.Where(c => c.FatherID == n.ID).Select(c => new UserMenuModel
                                   {
                                       key = c.key,
                                       CreateTime = c.CreateTime,
                                       guid = c.guid,
                                       Name = c.Name,
                                       FatherID = c.FatherID,
                                       Icon = c.Icon,
                                       Introduce = c.Introduce,
                                       Spread = c.Spread,
                                       Url = c.Url,
                                   }).ToList()
                               })
                               .OrderBy(n => n.Sort).ToPageAsync(request.PageIndex, request.PageSize);

                response.success = true;
                response.message = "获取成功！";
                response.data = pages;
                return response;

            }
            catch (Exception ex)
            {
                response.message = "获取失败！意外错误：" + ex.Message;
                return response;
            }
        }



        public async Task<ApiResult<string>> SaveAsync(UserMenuModel request)
        {
            ApiResult<string> response = new ApiResult<string>();
            try
            {
                if (string.IsNullOrEmpty(request.guid))
                {
                    UserMenu model = new UserMenu();
                    if (request.FatherID != null)
                    {

                        model.UserMenuID = request.FatherID;
                    }

                    model.Icon = request.Icon;
                    model.Introduce = request.Introduce;
                    model.Spread = request.Spread;
                    model.Url = request.Url;
                    model.Name = request.Name;
                    model.Sort = request.Sort;
                    await _unitofwork.RegisterNewAsync(model);
                }
                else
                {
                    var sguid = Guid.Parse(request.guid);
                    var model = Query().Where(n => n.Guid == sguid).FirstOrDefault();
                    if (model == null)
                    {
                        throw new Exception("未找到修改数据！！");
                    }
                    if (request.FatherID != null)
                    {

                        model.UserMenuID = request.FatherID;
                    }
                    else
                    {
                        model.UserMenuID = null;
                    }
                    model.Icon = request.Icon;
                    model.Introduce = request.Introduce;
                    model.Spread = request.Spread;
                    model.Url = request.Url;
                    model.Name = request.Name;
                    model.Sort = request.Sort;
                    _unitofwork.RegisterDirty(model);

                }

                var b = await _unitofwork.CommitAsync();

                response.success = b;
                response.message = b ? "保存成功！" : "保存失败";
                return response;
            }
            catch (Exception ex)
            {

                response.message = "发生错误：" + ex.Message;
                return response;
            }
        }


        public ApiResult<List<UserActionResponse>> GetFatherMenu()
        {
            ApiResult<List<UserActionResponse>> response = new ApiResult<List<UserActionResponse>>();
            try
            {
                var pages = Query().Where(n => n.UserMenuID == null).Select(n => new UserActionResponse
                {
                    id = n.ID,
                    name = n.Name,

                }).ToList();

                response.success = true;
                response.message = "获取成功！";
                response.data = pages;
                return response;

            }
            catch (Exception ex)
            {
                response.message = "获取失败！意外错误：" + ex.Message;
                return response;
            }
        }
    }
}
